import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Space,
  Tag,
  Modal,
  Form,
  Input,
  Select,
  message,
  Card,
  Row,
  Col,
  Switch,
  Avatar,
  Popconfirm,
  DatePicker,
  Descriptions
} from 'antd';
import {
  SearchOutlined,
  EyeOutlined,
  UserOutlined,
  LockOutlined,
  StopOutlined
} from '@ant-design/icons';
import { userAPI, roleAPI } from '../../services/api';
import { useAdminAuth } from '../../hooks/useAuth';

const { Option } = Select;
const { RangePicker } = DatePicker;

const AdminUsers = () => {
  const [loading, setLoading] = useState(false);
  const [users, setUsers] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [searchForm] = Form.useForm();
  const [passwordForm] = Form.useForm();
  const [detailVisible, setDetailVisible] = useState(false);
  const [passwordVisible, setPasswordVisible] = useState(false);
  const [selectedUser, setSelectedUser] = useState(null);
  const { hasAdminPermission } = useAdminAuth();

  // 统一的按钮样式
  const buttonStyle = {
    height: '32px',
    fontSize: '14px',
    fontWeight: '400',
    borderRadius: '6px'
  };

  useEffect(() => {
    loadUsers();
  }, []);

  const loadUsers = async (params = {}) => {
    setLoading(true);
    try {
      const response = await userAPI.getUsers({
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...params
      });
      
      if (response.success) {
        setUsers(response.data.list);
        setPagination(prev => ({
          ...prev,
          total: response.data.total
        }));
      }
    } catch (error) {
      message.error('加载用户列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = () => {
    const values = searchForm.getFieldsValue();
    setPagination(prev => ({ ...prev, current: 1 }));
    loadUsers(values);
  };

  const handleReset = () => {
    searchForm.resetFields();
    setPagination(prev => ({ ...prev, current: 1 }));
    loadUsers();
  };

  const handleViewDetail = (user) => {
    setSelectedUser(user);
    setDetailVisible(true);
  };

  const handleResetPassword = (user) => {
    setSelectedUser(user);
    passwordForm.resetFields();
    setPasswordVisible(true);
  };

  const handlePasswordSubmit = async () => {
    try {
      const values = await passwordForm.validateFields();
      
      // 这里应该调用实际的重置密码API
      message.success(`用户 ${selectedUser.nickname || selectedUser.username} 的密码已重置为：${values.newPassword}`);
      setPasswordVisible(false);
      passwordForm.resetFields();
    } catch (error) {
      message.error('密码重置失败');
    }
  };

  const handleStatusChange = async (userId, checked, userName) => {
    try {
      const status = checked ? 'active' : 'disabled';
      const actionText = checked ? '启用' : '封禁';
      
      // 这里应该调用实际的API来更新用户状态
      message.success(`用户 ${userName} 已${actionText}`);
      
      // 更新本地状态
      setUsers(prev => prev.map(user => 
        user.id === userId ? { ...user, status } : user
      ));
    } catch (error) {
      message.error('操作失败');
    }
  };

  const getLevelColor = (level) => {
    const levelMap = {
      'VIP': 'gold',
      '普通会员': 'blue',
      '铜牌会员': '#cd7f32',
      '银牌会员': 'silver',
      '金牌会员': 'gold'
    };
    return levelMap[level] || 'default';
  };

  const columns = [
    {
      title: '头像',
      dataIndex: 'avatar',
      key: 'avatar',
      width: 80,
      render: (avatar, record) => (
        <Avatar 
          size={40} 
          src={avatar} 
          icon={<UserOutlined />}
        />
      ),
    },
    {
      title: '用户信息',
      key: 'userInfo',
      render: (_, record) => (
        <div>
          <div style={{ fontWeight: 'bold' }}>{record.nickname || record.username}</div>
          <div style={{ fontSize: '12px', color: '#999' }}>@{record.username}</div>
        </div>
      ),
      width: 100,
    },
    {
      title: '联系方式',
      key: 'contact',
      render: (_, record) => (
        <div>
          <div>{record.phone || '-'}</div>
          <div style={{ fontSize: '12px', color: '#999' }}>{record.email || '-'}</div>
        </div>
      ),
      width: 180,
    },
    {
      title: '会员等级',
      dataIndex: 'level',
      key: 'level',
      render: (level) => (
        <Tag color={getLevelColor(level)}>{level}</Tag>
      ),
      width: 100,
    },
    {
      title: '积分',
      dataIndex: 'points',
      key: 'points',
      sorter: true,
      render: (points) => points || 0,
      width: 100,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={status === 'active' ? 'green' : 'red'}>
          {status === 'active' ? '正常' : '封禁'}
        </Tag>
      ),
      width: 100,
    },
    {
      title: '注册时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (time) => new Date(time).toLocaleDateString(),
      sorter: true,
      width: 150,
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 250,
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            icon={<EyeOutlined />}
            size="small"
            onClick={() => handleViewDetail(record)}
            style={buttonStyle}
          >
            查看
          </Button>
          
          {hasAdminPermission('user:reset') && (
            <Button
              type="link"
              icon={<LockOutlined />}
              size="small"
              onClick={() => handleResetPassword(record)}
              style={buttonStyle}
            >
              重置密码
            </Button>
          )}
          
          {hasAdminPermission('user:disable') && (
            <Popconfirm
              title={`确定要${record.status === 'active' ? '封禁' : '启用'}这个用户吗？`}
              description={record.status === 'active' ? '封禁后用户将无法登录系统' : '启用后用户可以正常使用系统'}
              onConfirm={() => 
                handleStatusChange(
                  record.id, 
                  record.status !== 'active',
                  record.nickname || record.username
                )
              }
            >
              <Button
                type="link"
                icon={<StopOutlined />}
                size="small"
                style={{
                  ...buttonStyle,
                  color: record.status === 'active' ? '#f5222d' : '#52c41a'
                }}
              >
                {record.status === 'active' ? '封禁' : '启用'}
              </Button>
            </Popconfirm>
          )}
          
          <Switch
            size="small"
            checked={record.status === 'active'}
            onChange={(checked) => 
              handleStatusChange(
                record.id, 
                checked,
                record.nickname || record.username
              )
            }
          />
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card style={{ marginBottom: 16 }}>
        <Form
          form={searchForm}
          layout="horizontal"
          onFinish={handleSearch}
        >
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item name="keyword" label="关键词">
                <Input placeholder="搜索用户名、昵称、手机号" />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="level" label="会员等级">
                <Select placeholder="选择会员等级" allowClear>
                  <Option value="普通会员">普通会员</Option>
                  <Option value="铜牌会员">铜牌会员</Option>
                  <Option value="银牌会员">银牌会员</Option>
                  <Option value="金牌会员">金牌会员</Option>
                  <Option value="VIP">VIP</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="status" label="状态">
                <Select placeholder="选择状态" allowClear>
                  <Option value="active">正常</Option>
                  <Option value="disabled">封禁</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Space>
                <Button 
                  type="primary" 
                  htmlType="submit" 
                  icon={<SearchOutlined />}
                  style={buttonStyle}
                >
                  搜索
                </Button>
                <Button onClick={handleReset} style={buttonStyle}>重置</Button>
              </Space>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="dateRange" label="注册时间">
                <RangePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Card>

      <Card title="用户管理">
        <Table
          columns={columns}
          dataSource={users}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, pageSize) => {
              setPagination(prev => ({ ...prev, current: page, pageSize }));
              loadUsers({ page, pageSize });
            },
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 用户详情模态框 */}
      <Modal
        title="用户详情"
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailVisible(false)} style={buttonStyle}>
            关闭
          </Button>
        ]}
        width={600}
      >
        {selectedUser && (
          <div>
            <div style={{ textAlign: 'center', marginBottom: 24 }}>
              <Avatar 
                size={80} 
                src={selectedUser.avatar} 
                icon={<UserOutlined />}
              />
              <h3 style={{ margin: '16px 0 8px 0' }}>{selectedUser.nickname || selectedUser.username}</h3>
              <Space>
                <Tag color={getLevelColor(selectedUser.level)}>
                  {selectedUser.level}
                </Tag>
                <Tag color={selectedUser.status === 'active' ? 'green' : 'red'}>
                  {selectedUser.status === 'active' ? '正常' : '封禁'}
                </Tag>
              </Space>
            </div>
            
            <Descriptions bordered column={2}>
              <Descriptions.Item label="用户名">{selectedUser.username}</Descriptions.Item>
              <Descriptions.Item label="昵称">{selectedUser.nickname || '-'}</Descriptions.Item>
              <Descriptions.Item label="手机号">{selectedUser.phone || '-'}</Descriptions.Item>
              <Descriptions.Item label="邮箱">{selectedUser.email || '-'}</Descriptions.Item>
              <Descriptions.Item label="会员等级">{selectedUser.level}</Descriptions.Item>
              <Descriptions.Item label="当前积分">{selectedUser.points || 0}</Descriptions.Item>
              <Descriptions.Item label="账户状态">
                <Tag color={selectedUser.status === 'active' ? 'green' : 'red'}>
                  {selectedUser.status === 'active' ? '正常' : '封禁'}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="注册时间">
                {new Date(selectedUser.createTime).toLocaleString()}
              </Descriptions.Item>
              <Descriptions.Item label="最后登录" span={2}>
                {selectedUser.lastLoginTime ? 
                  new Date(selectedUser.lastLoginTime).toLocaleString() : '从未登录'}
              </Descriptions.Item>
            </Descriptions>
          </div>
        )}
      </Modal>

      {/* 重置密码模态框 */}
      <Modal
        title="重置用户密码"
        open={passwordVisible}
        onOk={handlePasswordSubmit}
        onCancel={() => setPasswordVisible(false)}
        destroyOnClose
        okButtonProps={{ style: buttonStyle }}
        cancelButtonProps={{ style: buttonStyle }}
      >
        <div style={{ marginBottom: 16 }}>
          <p>将为用户 <strong>{selectedUser?.nickname || selectedUser?.username}</strong> 重置密码</p>
        </div>
        
        <Form
          form={passwordForm}
          layout="vertical"
        >
          <Form.Item
            name="newPassword"
            label="新密码"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 6, message: '密码至少6位' },
              { pattern: /^(?=.*[a-zA-Z])(?=.*\d).+$/, message: '密码必须包含字母和数字' }
            ]}
          >
            <Input.Password 
              placeholder="请输入新密码（至少6位，包含字母和数字）"
              prefix={<LockOutlined />}
            />
          </Form.Item>
          
          <Form.Item
            name="confirmPassword"
            label="确认密码"
            dependencies={['newPassword']}
            rules={[
              { required: true, message: '请确认新密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password 
              placeholder="请再次输入新密码"
              prefix={<LockOutlined />}
            />
          </Form.Item>

          <Form.Item
            name="notifyUser"
            label="通知方式"
            initialValue="system"
          >
            <Select>
              <Option value="system">系统通知</Option>
              <Option value="sms">短信通知</Option>
              <Option value="email">邮件通知</Option>
              <Option value="none">不通知</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default AdminUsers;